//
//  NetworkTools.swift
//  GZWeibo
//
//  Created by Apple on 15/9/22.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    // OC 的 typedefine 非常类似，定义数据类型
    // 网络请求完成回调的数据类型 - 首字母要大写
    typealias RequestFinishedCallBack = (result: AnyObject?, error: NSError?) -> ()
    
    // 网络工具单例
    static let sharedTools: NetworkTools = {
        let instance = NetworkTools(baseURL: nil)
        
        // 设置反序列化格式 - Xcode 会自动将 OC 代码中的 NSSet 转换成 Set 类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    // MARK: - 应用程序信息
    private let appKey = "2961516840"
    private let appSecret = "b1ff9aa47e116910ae3652a280c87e2c"
    
    // 授权回调地址
    let redirectURL = "https://www.baidu.com/"
    
    // OAuth 登录URL地址    
    /// 计算型属性，类似于函数，必须有返回值，同时不能有参数，使用频率，使用属性，代码的语义会更清晰
    var oauthURL : NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectURL)"
        
        return NSURL(string: urlString)!
    }
    
    // 使用code 加载Token
    func loadAccessToken(code: String, finished: RequestFinishedCallBack) {
        let params = ["client_id": appKey,
                      "client_secret": appSecret,
                      "redirect_uri": redirectURL,
                      "grant_type": "authorization_code",
                      "code": code]
        
    request(.POST, urlString: "https://api.weibo.com/oauth2/access_token", parameters: params, finished: finished)
    }



private func request(method: RequestMethod, urlString: String, parameters:[String: AnyObject]?, finished: RequestFinishedCallBack) {
    
    // 闭包是提前准备好的代码, 可以当作参数传递
    let success = { (task: NSURLSessionDataTask, result: AnyObject) -> () in
        finished(result: result, error: nil)
    }
    let failure = { (task: NSURLSessionDataTask, error: NSError) -> () in
        print(error)
        finished(result: nil, error: error)
    }
    
    if method == RequestMethod.GET {
        GET(urlString, parameters: parameters, success: success, failure: failure)
    } else {
        POST(urlString, parameters: parameters, success: success, failure: failure)
    }
    }
    

}



